import datetime
import os
from nptdms import TdmsFile
from multiprocessing import Process, Queue
from openpyxl import Workbook,load_workbook
import numpy as np


class Converter:
    def __init__(self, resource_path, save_path):
        self.read_path = resource_path
        self.save_path = save_path
        self.data = self.all_file = resource_path
        self.input_queue = Queue()
        self.output_queue = Queue()
        # self.wb1 = Workbook()
        # self.ws = self.wb1.active

    def tdms2txt(self, tdms_path: str):
        file_full_path = tdms_path
        with open(os.path.join(self.save_path,f'{os.path.basename(file_full_path)}_9235.txt'), "w+") as txtfile_9235:
            with open(os.path.join(self.save_path,f'{os.path.basename(file_full_path)}_9205.txt'), "w+") as txtfile_9205:
                with TdmsFile.read(f"{file_full_path}") as tdms_file:
                    # 9235 相关数据
                    group_9235 = tdms_file.groups()[0]
                    channels_9235 = group_9235.channels()
                    data_lenth_9235 = channels_9235[0].data.size
                    data_width_9235 = len(channels_9235)
                    # 9205 相关数据
                    group_9205 = tdms_file["9205电压"]
                    channels_9205 = group_9205.channels()
                    data_lenth_9205 = channels_9205[0].data.size
                    data_width_9205 = len(channels_9205)
                    # 9235 表头写入
                    for channel_9235 in channels_9235:
                        txtfile_9235.write(f"{channel_9235.name}\t")
                    txtfile_9235.write("\n")
                    # 9205 表头写入
                    for channel_9205 in channels_9205:
                        txtfile_9205.write(f"{channel_9205.name}\t")
                    txtfile_9205.write("\n")
                    # 9235 数据写入
                    for row_index in range(data_lenth_9235):
                        for column_index in range(data_width_9235):
                            txtfile_9235.write(f"{channels_9235[column_index].data[row_index]}\t")
                        abslute_time = channel_9235.properties['wf_start_time'].astype(datetime.datetime)
                        txtfile_9235.write(f"{channel_9235.time_track(absolute_time=True)[column_index]}\n")
                    # 9205 数据写入
                    for row_index in range(data_lenth_9205):
                        for column_index in range(data_width_9205):
                            txtfile_9205.write(f"{channels_9205[column_index].data[row_index]}\t")
                        txtfile_9205.write("\n")


        wf_start_time_9235 = (channel_9235.properties['wf_start_time'].astype(datetime.datetime))
        wf_start_time_9205 = (channel_9205.properties['wf_start_time'].astype(datetime.datetime))

        return ([
            txtfile_9235.name,
            wf_start_time_9235,
            channel_9235.properties['wf_samples'],
            data_lenth_9235,
            txtfile_9205.name,
            wf_start_time_9205,
            channel_9205.properties['wf_samples'],
            data_lenth_9205
        ])

    def set_process(self):
        processes = []
        for _ in range(4):
            p = Process(target=self.worker)
            p.start()
            processes.append(p)

        # 将数据放入输入队列
        for item in self.data:
            self.input_queue.put(item)

        # 添加哨兵值，通知工作进程结束
        for _ in range(4):
            self.input_queue.put(None)

        # 收集结果
        results = []
        for _ in range(len(self.data)):
            results.append(self.output_queue.get())

        # 等待所有进程完成
        for p in processes:
            p.join()

        print(results)  # 输出: [1, 4, 9, 16, 25]
        try:
            wb = load_workbook("record.xlsx")
        except:
            wb = Workbook()
        ws = wb.active
        ws._current_row = ws.max_row
        for d in results:
            ws.append(d)
        wb.save("record.xlsx")
        wb.close()

    def worker(self):
        while True:
            item = self.input_queue.get()
            if item is None:  # 哨兵值，表示任务结束
                break
            # 处理项目
            result = self.tdms2txt(item)
            self.output_queue.put(result)


if __name__ == '__main__':
    mypath = r"E:\新采集软件数据集\ManWan-test-dataset"
    myc = Converter(mypath)
    myc.set_process()

    # 创建并启动4个工作进程
